const fs = require("fs");
const {Buffer} = require("buffer");

class NESParser
{
    // 读取头文件信息
    init(nesFile){
        this.nesFile = nesFile;
    }
    readNes(cb){
        fs.readFile(this.nesFile,(err,data)=>{
            if(err){
                console.log("read"+nesFile,"err",err);
            }
            this.buffer = data;
            cb();
        })  
    }
    h(){
        // 头部信息组织
        this.readNes(() => {
            console.log("buffer",this.buffer)
            // 8x16kb+16x8kb=128kb的程序+128kb的Chr
            let prgNum = this.buffer.readUInt8(4) 
            let chrNum = this.buffer.readUInt8(5);
            console.log("num",prgNum,chrNum);
            // 读取prg
            let prgStart = 16;
            let prgLength = prgNum * 16*1024;
            let prgBuffer = this.buffer.slice(prgStart,prgStart+prgLength + 1);
            let chrStart = prgStart + prgLength;
            console.log("prgBuffer",prgBuffer);
            let chrBuffer = this.buffer.slice(chrStart);
            console.log("chrBuffer",chrBuffer);
        })
    }
    
    hexToArray(d){
        let number = d.toString(16);
        console.log("hex",number & 0x4)
        return [
            number & 0x1 == 0x1 ? 1 : 0, 
            number & 0x2 == 0x2 ? 1 : 0,
            number & 0x4 == 0x4 ? 1 : 0, 
            number & 0x8 == 0x8 ? 1 : 0, 
            number & 0x10 == 0x10 ? 1 : 0, 
            number & 0x20 == 0x20 ? 1 : 0, 
            number & 0x40 == 0x40 ? 1 : 0,
            number & 0x80 == 0x80 ? 1 : 0,
        ]    
    }
    
}


let n = new NESParser();
n.init("../rom/热血高校足球.nes");
n.h();